
//930.和相同的二元子数组
class Solution {
    
public:
    int numSubarraysWithSum(vector<int>& nums, int goal) {
        int n = nums.size();

        //查找子数组和不超过tar的子数组个数
        function<int(int)> LessTar = [&](int tar)
        {
            int left = 0 ,right = 0;  
            int sum =0, ret = 0;
            for(int right = 0; right < n  ;right++)     //以right为右边界进行枚举
            {
                sum += nums[right];
                while(sum > tar && left <= right)       //子数组和>tar,进行收缩
                    sum -= nums[left++];
                ret += right - left +1;
            }
            return ret;
        };

        return LessTar(goal) - LessTar(goal-1);
    }
};